package com.ruoyi.analyse.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.DsClassStu;
import com.ruoyi.system.mapper.DsClassStuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.analyse.mapper.StudentProfileMapper;
import com.ruoyi.analyse.domain.StudentProfile;
import com.ruoyi.analyse.service.IStudentProfileService;

/**
 * 学生学情画像Service业务层处理
 *
 * @author ruoyi
 */
@Service
public class StudentProfileServiceImpl implements IStudentProfileService
{
    @Autowired
    private StudentProfileMapper studentProfileMapper;

    @Autowired
    private DsClassStuMapper dsClassStuMapper;
    /**
     * 查询学生学情画像
     *
     * @param profileId 学生学情画像主键
     * @return 学生学情画像
     */
    @Override
    public StudentProfile selectStudentProfileByProfileId(Long profileId)
    {
        return studentProfileMapper.selectStudentProfileByProfileId(profileId);
    }

    /**
     * 查询学生学情画像列表
     *
     * @param studentProfile 学生学情画像
     * @return 学生学情画像
     */
    @Override
    public List<StudentProfile> selectStudentProfileList(StudentProfile studentProfile)
    {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 如果不是管理员，则添加学院过滤条件
        if(!SecurityUtils.isAdmin(userId)){ // 或使用 SecurityUtils.isAdmin(loginUser.getUser().getUserId())
            studentProfile.setCollegeId(SecurityUtils.getLoginUser().getCollegeId());
        }
        return studentProfileMapper.selectStudentProfileList(studentProfile);
    }

    /**
     * 新增学生学情画像
     *
     * @param studentProfile 学生学情画像
     * @return 结果
     */
    @Override
    public int insertStudentProfile(StudentProfile studentProfile)
    {
        // 设置学院ID
        if (studentProfile.getCollegeId() == null) {
            studentProfile.setCollegeId(SecurityUtils.getLoginUser().getCollegeId());
        }
        studentProfile.setCreateTime(new Date());
        return studentProfileMapper.insertStudentProfile(studentProfile);
    }

    /**
     * 修改学生学情画像
     *
     * @param studentProfile 学生学情画像
     * @return 结果
     */
    @Override
    public int updateStudentProfile(StudentProfile studentProfile)
    {
        studentProfile.setUpdateTime(new Date());
        return studentProfileMapper.updateStudentProfile(studentProfile);
    }

    /**
     * 批量删除学生学情画像
     *
     * @param profileIds 需要删除的学生学情画像主键
     * @return 结果
     */
    @Override
    public int deleteStudentProfileByProfileIds(Long[] profileIds)
    {
        return studentProfileMapper.deleteStudentProfileByProfileIds(profileIds);
    }

    /**
     * 删除学生学情画像信息
     *
     * @param profileId 学生学情画像主键
     * @return 结果
     */
    @Override
    public int deleteStudentProfileByProfileId(Long profileId)
    {
        return studentProfileMapper.deleteStudentProfileByProfileId(profileId);
    }

    /**
     * 更新学生提问记录
     *
     * @param userName 用户名
     * @param subject 学科
     * @param complexity 复杂度
     * @return 结果
     */
    @Override
    public int updateStudentQuestionRecord(String userName, String subject, String complexity)
    {
        // 查询是否存在该学生记录
        StudentProfile studentProfile = studentProfileMapper.selectStudentProfileByUserName(userName);

        Date now = new Date();

        if (studentProfile == null) {
            // 创建新记录
            studentProfile = new StudentProfile();
            studentProfile.setUserName(userName);
            studentProfile.setTotalQuestions(1);
            studentProfile.setMainSubject(subject);
            studentProfile.setLastActiveTime(now);
            studentProfile.setCreateTime(now);
            studentProfile.setUpdateTime(now);

            // 根据复杂度更新相应的问题计数
            if ("SIMPLE".equals(complexity)) {
                studentProfile.setSimpleQuestions(1);
                studentProfile.setMediumQuestions(0);
                studentProfile.setComplexQuestions(0);
            } else if ("MEDIUM".equals(complexity)) {
                studentProfile.setSimpleQuestions(0);
                studentProfile.setMediumQuestions(1);
                studentProfile.setComplexQuestions(0);
            } else if ("COMPLEX".equals(complexity)) {
                studentProfile.setSimpleQuestions(0);
                studentProfile.setMediumQuestions(0);
                studentProfile.setComplexQuestions(1);
            }

            return studentProfileMapper.insertStudentProfile(studentProfile);
        } else {
            // 更新现有记录
            studentProfile.setTotalQuestions(studentProfile.getTotalQuestions() + 1);
            studentProfile.setLastActiveTime(now);
            studentProfile.setUpdateTime(now);

            // 更新主要学科(如果当前学科与现有不同，可以根据实际需求决定是否更新)
            if (subject != null && !subject.equals(studentProfile.getMainSubject())) {
                // 简单实现: 更新为最近提问的学科
                studentProfile.setMainSubject(subject);
            }

            // 根据复杂度更新相应的问题计数
            if ("SIMPLE".equals(complexity)) {
                studentProfile.setSimpleQuestions(studentProfile.getSimpleQuestions() + 1);
            } else if ("MEDIUM".equals(complexity)) {
                studentProfile.setMediumQuestions(studentProfile.getMediumQuestions() + 1);
            } else if ("COMPLEX".equals(complexity)) {
                studentProfile.setComplexQuestions(studentProfile.getComplexQuestions() + 1);
            }

            return studentProfileMapper.updateStudentProfile(studentProfile);
        }
    }

    /**
     * 获取学生学习画像
     *
     * @param userName 用户名
     * @return 学生画像数据
     */
    @Override
    public Map<String, Object> getStudentLearningProfile(String userName)
    {
        Map<String, Object> profile = new HashMap<>();

        // 获取学生基本信息
        StudentProfile studentProfile = studentProfileMapper.selectStudentProfileByUserName(userName);

        if (studentProfile != null) {
            profile.put("userName", studentProfile.getUserName());
            profile.put("totalQuestions", studentProfile.getTotalQuestions());
            profile.put("mainSubject", studentProfile.getMainSubject());
            profile.put("lastActiveTime", studentProfile.getLastActiveTime());

            // 问题复杂度分布
            Map<String, Object> complexityDistribution = new HashMap<>();
            int simpleCount = studentProfile.getSimpleQuestions() != null ? studentProfile.getSimpleQuestions() : 0;
            int mediumCount = studentProfile.getMediumQuestions() != null ? studentProfile.getMediumQuestions() : 0;
            int complexCount = studentProfile.getComplexQuestions() != null ? studentProfile.getComplexQuestions() : 0;

            complexityDistribution.put("simple", simpleCount);
            complexityDistribution.put("medium", mediumCount);
            complexityDistribution.put("complex", complexCount);

            profile.put("complexityDistribution", complexityDistribution);

            // 计算学习能力评分(简单示例)
            double learningScore = calculateLearningScore(simpleCount, mediumCount, complexCount);
            profile.put("learningScore", learningScore);

            // 评估学习状态
            String learningStatus = evaluateLearningStatus(learningScore, studentProfile.getLastActiveTime());
            profile.put("learningStatus", learningStatus);
        } else {
            profile.put("message", "该学生暂无学习记录");
        }

        return profile;
    }

    /**
     * 获取最活跃的学生列表
     *
     * @param limit 限制数量
     * @return 活跃学生列表
     */
    @Override
    public List<Map<String, Object>> getTopActiveStudents(int limit, Long classId)
    {
        List<StudentProfile> activeStudents;
        if (classId != null) {
            // 使用子查询直接获取结果
            activeStudents = studentProfileMapper.selectTopActiveStudentsByClassId(limit, classId);
        } else {
            // 不过滤班级，获取所有学生
            activeStudents = studentProfileMapper.selectTopActiveStudents(limit);
        }List<Map<String, Object>> result = new ArrayList<>();

        for (StudentProfile student : activeStudents) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", student.getUserName());
            map.put("totalQuestions", student.getTotalQuestions());
            map.put("mainSubject", student.getMainSubject());
            map.put("lastActiveTime", student.getLastActiveTime());

            // 计算学习能力评分
            int simpleCount = student.getSimpleQuestions() != null ? student.getSimpleQuestions() : 0;
            int mediumCount = student.getMediumQuestions() != null ? student.getMediumQuestions() : 0;
            int complexCount = student.getComplexQuestions() != null ? student.getComplexQuestions() : 0;
            double learningScore = calculateLearningScore(simpleCount, mediumCount, complexCount);
            map.put("learningScore", learningScore);

            result.add(map);
        }

        return result;
    }

    /**
     * 计算学习能力评分
     *
     * @param simpleCount 简单问题数
     * @param mediumCount 中等问题数
     * @param complexCount 复杂问题数
     * @return 学习能力评分
     */
    private double calculateLearningScore(int simpleCount, int mediumCount, int complexCount) {
        // 简单算法: 根据不同复杂度的问题加权计算
        // 简单问题权重1, 中等问题权重2, 复杂问题权重3
        int totalQuestions = simpleCount + mediumCount + complexCount;

        if (totalQuestions == 0) {
            return 0;
        }

        int weightedScore = simpleCount * 1 + mediumCount * 2 + complexCount * 3;
        // 归一化到100分制
        double normalizedScore = Math.min(100, (weightedScore * 100.0) / (totalQuestions * 3.0));

        return Math.round(normalizedScore * 10) / 10.0; // 保留一位小数
    }

    /**
     * 评估学习状态
     *
     * @param learningScore 学习能力评分
     * @param lastActiveTime 最后活跃时间
     * @return 学习状态评估
     */
    private String evaluateLearningStatus(double learningScore, Date lastActiveTime) {
        // 根据分数和活跃度评估学习状态
        long daysSinceLastActive = (new Date().getTime() - lastActiveTime.getTime()) / (1000 * 60 * 60 * 24);

        if (learningScore >= 80) {
            if (daysSinceLastActive <= 7) {
                return "优秀 - 学习能力强,学习频率高";
            } else {
                return "良好 - 学习能力强,但最近活跃度较低";
            }
        } else if (learningScore >= 60) {
            if (daysSinceLastActive <= 7) {
                return "良好 - 学习持续进行中";
            } else {
                return "一般 - 需要提高学习能力和频率";
            }
        } else {
            if (daysSinceLastActive <= 7) {
                return "需要提升 - 建议关注基础知识点";
            } else {
                return "需要关注 - 学习状态不佳,建议加强学习";
            }
        }
    }
}
